<template>
  <div>
    <van-search
      v-model="keyword"
      show-action
      shape="round"
      background="#f88"
      label="地址"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="his-wrap">
      <div class="his-text">
        <h4>搜索记录</h4>
      </div>
      <div v-if="!history.length" style="font-size:14px;color:#ccc;margin:20px">暂无搜索记录</div>
      <div class="history">
        <div class="his" @click="hisClick(his)"  v-for="his in history" :key="his">
          {{ his }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      keyword: '',
      history: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    // 点击历史记录回到之前的搜索页
    hisClick (word) {
      // 这个word参数是当前点击的那个历史记录,
      // console.log(word)
      // 把输入进去的值keyword变成历史记录的word
      this.keyword = word
      this.onSearch()
    },
    onSearch () {
      // 存储 搜索记录
      // 先取出来转换成数组,操作数组JSON.stringify存回去
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      his.unshift(this.keyword)
      // 相同的历史记录去重 set可以展开去除重复的项
      his = [...new Set(his)]
      // 如果超出数组规定的长度,就删除数据尾部的记录
      if (his.length >= 3) {
        his.length = 3
      }
      // 存回去
      localStorage.setItem('his', JSON.stringify(his))
      // 进入搜索结果页 并传递关键字
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: this.keyword
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.his-wrap{

  .his-text{
    width: 100px;
    height: 30px;
    border-radius: 15px;
    text-align: center;
    line-height: 30px;
    color: #fff;
    background-color: rgb(245, 170, 170);
    font-size: 14px;
    margin-top: 10px;
  }
  .history{
    margin-top: 20px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    color: #ccc;
    .his{
      background-color: rgb(245, 214, 214);
      padding: 5px 15px;
      margin-top: 10px;
      margin-left: 10px;
    }
  }
}
</style>
